package com.gack.netty.encoderAndDecoder.encoder;

import com.gack.netty.encoderAndDecoder.constract.SerialConstract;
import com.gack.netty.proto.MessageModule.Message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

/**
 * 
* @ClassName: MyEncoder 
* @Description: TODO(自定义解析器) 
* @author (ZhangXinYu)  
* @date 2018年9月6日 下午2:54:15 
* @version V1.0
 */
public class MyEncoder extends MessageToByteEncoder<Message>{

	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
		// 数据包头
		out.writeInt(SerialConstract.PACKAGE_HEADER);

		// 数据
		byte[] dataBytes = msg.toByteArray();
		ByteBuf dataBuf = Unpooled.buffer(dataBytes.length);
		
		// 数据内容 >> 字符串类型前面写入 int 代表字符串长度 便于解析
		dataBuf.writeInt(msg.getMsgType());
		byte[] contentBytes = msg.getContent().getBytes(CharsetUtil.UTF_8);
		dataBuf.writeInt(contentBytes.length);
		dataBuf.writeBytes(contentBytes);
		dataBuf.writeLong(msg.getTimestamp());
		byte[] equipmentBytes = msg.getEquipment().getBytes(CharsetUtil.UTF_8);
		dataBuf.writeInt(equipmentBytes.length);
		dataBuf.writeBytes(equipmentBytes);
		
		// 写入数据长度
		out.writeInt(dataBuf.readableBytes());
		// 写入数据
		out.writeBytes(dataBuf);
	}
	
}
